import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUser } from '@/stores/user'
const errorLang = {
  'zh-CN': 'cn_message',
  'en-US': 'en_message'
}
const lang = 'en-US'
// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests,
  timeout: 60000
})

// request interceptor
service.interceptors.request.use((config) => {
  if (config.method === 'get') {
    config.params = {
      ...config.params,
      timestamp: new Date().getTime()
    }
  }
  config.headers = {
    server: 1,
    Authorization: "Bearer " + localStorage.getItem("token")
  }
  return config
})

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code && res.code !== 1) {
      if ([421].includes(res.code)) {
        // token失效
        const user_store = useUser()
        user_store.logOut()
        setTimeout(()=>{
          location.reload()
        })
        ElMessage({
          message: res.msg || 'Error',
          type: 'error'
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  (error) => {
    ElMessage({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
